package com.itheima.rabbitmq;

import com.itheima.domain.entity.SeckillVoucher;
import com.itheima.domain.entity.VoucherOrder;
import com.itheima.service.ISeckillVoucherService;
import com.itheima.service.IVoucherOrderService;
import com.rabbitmq.client.Channel;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class OrderCancelListener {
    @Resource
    private IVoucherOrderService voucherOrderService;
    @Resource
    private ISeckillVoucherService seckillVoucherService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 监听 order.cancel.queue
     * 这个方法会在订单创建1分钟后被触发
     */
    @RabbitListener(queues = "order.cancel.queue")
    public void handleOrderCancel(Long orderId, Channel channel, Message message) {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            log.info("========== 订单超时检查 ==========");
            log.info("订单ID: {}", orderId);
            // 1. 查询订单
            VoucherOrder order = voucherOrderService.getById(orderId);
            if (order == null) {
                log.warn("订单不存在，orderId={}", orderId);
                channel.basicAck(deliveryTag, false);
                return;
            }
            // 2. 检查订单支付状态
            Integer status = order.getStatus();
            if (status == 2) {
                // 已支付，无需取消
                log.info("订单已支付，无需取消");
            } else if (status == 1) {
                // 未支付，执行取消
                log.warn("订单未支付，执行自动取消");
                // 3. 取消订单
                cancelOrder(order);
                log.info("订单已取消，库存已恢复");
            } else {
                log.info("订单状态：{}，无需处理", status);
            }

            // 4. 确认消息
            channel.basicAck(deliveryTag, false);

            log.info("==========================================\n");

        } catch (Exception e) {
            log.error("处理订单取消失败", e);
            try {
                channel.basicAck(deliveryTag, false);
            } catch (Exception ex) {
                log.error("ACK失败", ex);
            }
        }
    }

    /**
     * 取消订单
     */
    private void cancelOrder(VoucherOrder order) {
        // 1. 更新订单状态为"已取消"
        VoucherOrder update = VoucherOrder.builder().status(4).build();
        update.setId(order.getId());
        voucherOrderService.updateById(update);
        stringRedisTemplate.opsForSet().remove("seckill:order:" + order.getVoucherId(), order.getUserId().toString());
        // 2. 恢复优惠券库存
        seckillVoucherService.lambdaUpdate()
                .eq(SeckillVoucher::getVoucherId, order.getVoucherId())
                .setSql("stock = stock + 1")
                .update();
        stringRedisTemplate.opsForValue().set("seckill:stock:" + order.getVoucherId(),seckillVoucherService.getById(order.getVoucherId()).getStock().toString());
        log.info("订单已取消，订单ID: {}", order.getId());
    }
}
